<template>
  <div class="bre-toolbar__optbtn__lab" @click="handleClick">视频</div>
  <BreModal v-model="modalDisplay" title="添加视频卡片">
    <div class="bre-link-modal__form">
      <div class="bre-input medium">
        <BreInput
          v-model="form.link"
          placeholder="请输入bv号(如：bvxxxxxxx)、av号或视频链接"
          size="medium"
        />
      </div>
      <div class="bre-link-modal__form__btns">
        <BreButton
          size="small"
          type="primary"
          @click="handleEnter"
          class="bre-link-modal__btn"
        >
          确认
        </BreButton>
        <BreButton
          size="small"
          type="grey"
          @click="handleCancel"
          class="bre-link-modal__btn"
        >
          取消
        </BreButton>
      </div>
    </div>
  </BreModal>
</template>
<script setup lang="ts">
import BreInput from '../../components/BreInput.vue'
import BreButton from '../../components/BreButton.vue'
import BreModal from '../../components/BreModal.vue'
import { ref, shallowRef, inject } from 'vue'
import Quill from 'quill'
const QuillEditor = inject('QuillEditor', shallowRef<Quill>())

const modalDisplay = ref(false)
const form = ref({
  link: 'https://www.bilibili.com/video/BV1M453zvEr9/',
})
const handleClick = () => {
  modalDisplay.value = true
}
const handleEnter = () => {
  try {
    const itemId = validator(form.value.link) //返回商品卡片id
    // 请求接口获取卡片信息
    QuillEditor.value?.insertVideoCard({
      id: `${itemId}`, //卡片对应类型id
      alt: 'undefined',
      size: null,
    })
    modalDisplay.value = false
  } catch (error) {
    console.warn(error)
  }
}
const handleCancel = () => {
  form.value.link = ''
  modalDisplay.value = false
}
const validator = (t: string) => {
  if (!(t = t.trim())) throw new Error('请输入视频链接')
  let match = t.match(/(AV|av|Av|aV)[0-9]+/)
  if (match) return match[0]
  match = t.match(/(BV|bv|Bv|bV)1[1-9A-NP-Za-km-z]{9}/)
  if (match) return match[0]
  match = t.match(/^https?:\/\/[\w./]{1,}\/((av\d+)|((bv|BV)1\w{9}))/i)
  if (match) return match[1]
  throw new Error('无效的视频信息')
}
</script>
<style lang="scss" scoped></style>
